<template>
  <div class="product-detail">
    <!-- 商品主要信息 -->
    <section class="product-main container mx-auto px-4 py-8">
      <div class="main-content">
        <!-- 左侧图片展示 -->
        <div class="product-gallery">
          <el-carousel
            trigger="click"
            :autoplay="false"
            indicator-position="outside"
            height="400px"
            class="main-carousel"
          >
            <el-carousel-item v-for="image in product.images" :key="image">
              <el-image
                :src="image"
                fit="contain"
                :preview-src-list="product.images"
              />
            </el-carousel-item>
          </el-carousel>

          <div class="thumbnail-list">
            <div
              v-for="(image, index) in product.images"
              :key="index"
              class="thumbnail-item"
              :class="{ active: currentImageIndex === index }"
              @click="currentImageIndex = index"
            >
              <el-image :src="image" fit="cover" />
            </div>
          </div>
        </div>

        <!-- 右侧商品信息 -->
        <div class="product-info">
          <h1 class="product-title">{{ product.title }}</h1>

          <div class="product-meta">
            <div class="price-section">
              <div class="current-price"><em>¥</em>{{ product.price }}</div>
              <div class="original-price">
                原价: <span>¥{{ product.originalPrice }}</span>
              </div>
              <div class="tags">
                <el-tag
                  v-for="tag in product.tags.slice(0, 3)"
                  :key="tag"
                  :type="getTagType(tag)"
                  size="small"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>

            <div class="sales-info">
              <span>月销 {{ product.sales }}+</span>
              <span>累计评价 {{ product.reviewCount }}</span>
              <span>收藏 {{ product.favoriteCount }}</span>
            </div>
          </div>

          <!-- 商品规格 -->
          <div class="product-specs">
            <div
              v-for="spec in product.specs"
              :key="spec.name"
              class="spec-item"
            >
              <div class="spec-name">{{ spec.name }}</div>
              <div class="spec-values">
                <el-radio-group v-model="selectedSpecs[spec.name]">
                  <el-radio-button
                    v-for="value in spec.values"
                    :key="value.id"
                    :label="value.id"
                    :disabled="!value.stock"
                  >
                    {{ value.name }}
                  </el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </div>

          <!-- 购买数量 -->
          <div class="quantity-section">
            <span class="label">购买数量</span>
            <el-input-number
              v-model="quantity"
              :min="1"
              :max="99"
              size="large"
            />
            <span class="stock">库存 {{ product.stock }} 件</span>
          </div>

          <!-- 服务承诺 -->
          <div class="service-section">
            <div class="service-title">服务承诺</div>
            <div class="service-items">
              <div
                v-for="service in services"
                :key="service.name"
                class="service-item"
              >
                <el-icon><component :is="service.icon" /></el-icon>
                <span>{{ service.name }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button-group>
              <el-button type="primary" size="large" @click="handleAddToCart">
                加入购物车
              </el-button>
              <el-button type="danger" size="large" @click="handleBuyNow">
                立即购买
              </el-button>
            </el-button-group>
            <el-button
              :type="product.isFavorite ? 'danger' : 'default'"
              size="large"
              @click="handleFavorite"
            >
              <el-icon><Star /></el-icon>
              <span>{{ product.isFavorite ? "已收藏" : "收藏" }}</span>
            </el-button>
          </div>
        </div>
      </div>
    </section>

    <!-- 商品详情 -->
    <section class="product-content container mx-auto px-4 py-8">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="商品详情" name="detail">
          <div class="detail-content" v-html="product.detail"></div>
        </el-tab-pane>

        <el-tab-pane label="规格参数" name="params">
          <div class="params-content">
            <el-descriptions :column="2" border>
              <el-descriptions-item
                v-for="param in product.params"
                :key="param.name"
                :label="param.name"
              >
                {{ param.value }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>

        <el-tab-pane
          :label="'商品评价(' + product.reviewCount + ')'"
          name="reviews"
        >
          <!-- 评价概述 -->
          <div class="reviews-overview">
            <div class="rating-section">
              <div class="rating-score">
                {{ product.rating }}
                <small>分</small>
              </div>
              <el-rate
                v-model="product.rating"
                disabled
                show-score
                allow-half
              />
            </div>
            <div class="rating-tags">
              <el-tag
                v-for="tag in product.reviewTags"
                :key="tag.name"
                :type="tag.type"
                effect="plain"
                class="tag-item"
              >
                {{ tag.name }} ({{ tag.count }})
              </el-tag>
            </div>
          </div>

          <!-- 评价列表 -->
          <div class="reviews-list">
            <div
              v-for="review in product.reviews"
              :key="review.id"
              class="review-item"
            >
              <div class="review-header">
                <el-avatar :src="review.user.avatar" :size="40" />
                <div class="user-info">
                  <div class="user-name">{{ review.user.name }}</div>
                  <div class="review-meta">
                    <el-rate v-model="review.rating" disabled />
                    <time>{{ formatDate(review.createdAt) }}</time>
                    <span class="specs">{{ review.specs }}</span>
                  </div>
                </div>
              </div>

              <div class="review-content">
                <p class="review-text">{{ review.content }}</p>
                <div v-if="review.images?.length" class="review-images">
                  <el-image
                    v-for="image in review.images"
                    :key="image"
                    :src="image"
                    :preview-src-list="review.images"
                    class="image-item"
                  />
                </div>

                <div v-if="review.reply" class="review-reply">
                  <strong>商家回复：</strong>{{ review.reply }}
                </div>
              </div>
            </div>
          </div>

          <!-- 加载更多 -->
          <div v-if="hasMoreReviews" class="load-more">
            <el-button
              type="primary"
              text
              :loading="loadingReviews"
              @click="loadMoreReviews"
            >
              加载更多评价
            </el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </section>

    <!-- 推荐商品 -->
    <section class="recommendations container mx-auto px-4 py-8">
      <SectionTitle
        title="相关推荐"
        subtitle="RECOMMENDATIONS"
        :show-more="false"
      />

      <div class="recommendations-grid">
        <ProductCard
          v-for="item in recommendations"
          :key="item.id"
          :product="item"
          @favorite="handleFavorite"
          @add-to-cart="handleAddToCart"
          @buy-now="handleBuyNow"
        />
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user";
import {
  Star,
  ShieldCheck,
  TrendCharts,
  Van,
  Service,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 当前选中的图片索引
const currentImageIndex = ref(0);
// 选中的规格
const selectedSpecs = ref({});
// 购买数量
const quantity = ref(1);
// 当前标签页
const activeTab = ref("detail");
// 加载状态
const loadingReviews = ref(false);

// 服务承诺
const services = [
  { name: "正品保证", icon: "ShieldCheck" },
  { name: "极速退款", icon: "TrendCharts" },
  { name: "免费包邮", icon: "Van" },
  { name: "售后无忧", icon: "Service" },
];

// 商品数据
const product = ref({
  id: 1,
  title: "贵港特色手工艺品",
  price: 99,
  originalPrice: 129,
  sales: 235,
  stock: 999,
  rating: 4.7,
  reviewCount: 125,
  favoriteCount: 1688,
  isFavorite: false,
  tags: ["新品", "热销"],
  images: [
    "/images/products/product1-1.jpg",
    "/images/products/product1-2.jpg",
    "/images/products/product1-3.jpg",
  ],
  specs: [
    {
      name: "颜色",
      values: [
        { id: 1, name: "红色", stock: 100 },
        { id: 2, name: "蓝色", stock: 200 },
        { id: 3, name: "绿色", stock: 0 },
      ],
    },
    {
      name: "尺寸",
      values: [
        { id: 1, name: "S", stock: 100 },
        { id: 2, name: "M", stock: 200 },
        { id: 3, name: "L", stock: 300 },
      ],
    },
  ],
  detail: "<div>商品详情HTML内容</div>",
  params: [
    { name: "材质", value: "纯棉" },
    { name: "产地", value: "贵港" },
    { name: "工艺", value: "手工制作" },
  ],
  reviewTags: [
    { name: "质量好", count: 532, type: "success" },
    { name: "物流快", count: 423, type: "primary" },
    { name: "价格实惠", count: 321, type: "warning" },
  ],
  reviews: [
    {
      id: 1,
      user: {
        name: "用户***123",
        avatar: "/images/avatars/user1.jpg",
      },
      rating: 5,
      content: "商品质量非常好，包装也很精美，很满意的一次购物体验！",
      images: [
        "/images/reviews/review1-1.jpg",
        "/images/reviews/review1-2.jpg",
      ],
      specs: "颜色：红色，尺寸：M",
      createdAt: "2024-03-15T12:00:00",
      reply: "感谢您的支持，我们会继续提供优质的商品和服务！",
    },
  ],
});

// 推荐商品
const recommendations = ref([
  // ... 推荐商品数据
]);

// 是否有更多评价
const hasMoreReviews = computed(() => {
  return product.value.reviews.length < product.value.reviewCount;
});

// 获取标签类型
const getTagType = (tag) => {
  const tagTypes = {
    新品: "success",
    热销: "danger",
    促销: "warning",
    限量: "info",
  };
  return tagTypes[tag] || "primary";
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm");
};

// 检查登录状态
const checkLogin = async () => {
  if (!userStore.token) {
    try {
      await ElMessageBox.confirm("登录后才能继续操作，是否前往登录？", "提示", {
        confirmButtonText: "去登录",
        cancelButtonText: "取消",
        type: "warning",
      });
      router.push({
        path: "/login",
        query: { redirect: router.currentRoute.value.fullPath },
      });
      return false;
    } catch {
      return false;
    }
  }
  return true;
};

// 处理收藏
const handleFavorite = async () => {
  if (!(await checkLogin())) return;

  try {
    product.value.isFavorite = !product.value.isFavorite;
    ElMessage.success(product.value.isFavorite ? "收藏成功" : "已取消收藏");
  } catch (error) {
    product.value.isFavorite = !product.value.isFavorite;
    ElMessage.error("操作失败，请重试");
  }
};

// 处理加入购物车
const handleAddToCart = async () => {
  if (!(await checkLogin())) return;

  // 验证是否选择了所有规格
  if (!validateSpecs()) return;

  ElMessage.success("已加入购物车");
};

// 处理立即购买
const handleBuyNow = async () => {
  if (!(await checkLogin())) return;

  // 验证是否选择了所有规格
  if (!validateSpecs()) return;

  router.push({
    path: "/order/confirm",
    query: {
      products: JSON.stringify([
        {
          ...product.value,
          quantity: quantity.value,
          selectedSpecs: selectedSpecs.value,
        },
      ]),
    },
  });
};

// 验证规格是否已选择
const validateSpecs = () => {
  const unselectedSpecs = product.value.specs.filter(
    (spec) => !selectedSpecs.value[spec.name],
  );

  if (unselectedSpecs.length) {
    ElMessage.warning("请选择" + unselectedSpecs[0].name);
    return false;
  }

  return true;
};

// 加载更多评价
const loadMoreReviews = async () => {
  if (loadingReviews.value) return;

  loadingReviews.value = true;
  try {
    // TODO: 加载更多评价
    await new Promise((resolve) => setTimeout(resolve, 1000));
  } finally {
    loadingReviews.value = false;
  }
};
</script>

<style lang="scss" scoped>
.product-detail {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .product-main {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

    .main-content {
      @apply flex gap-8 p-6;

      .product-gallery {
        @apply w-[500px] flex-shrink-0;

        .main-carousel {
          @apply bg-white dark:bg-gray-800 rounded-lg overflow-hidden
                 border border-gray-200 dark:border-gray-700;
        }

        .thumbnail-list {
          @apply flex gap-2 mt-4;

          .thumbnail-item {
            @apply w-20 h-20 rounded-lg overflow-hidden cursor-pointer
                   border-2 border-transparent transition-all duration-300
                   hover:border-primary-500 dark:hover:border-primary-400;

            &.active {
              @apply border-primary-500 dark:border-primary-400;
            }
          }
        }
      }

      .product-info {
        @apply flex-1 min-w-0;

        .product-title {
          @apply text-2xl font-bold text-gray-900 dark:text-white mb-6;
        }

        .product-meta {
          @apply mb-8;

          .price-section {
            @apply mb-4;

            .current-price {
              @apply text-3xl font-bold text-primary-600 dark:text-primary-400;

              em {
                @apply text-lg font-normal;
              }
            }

            .original-price {
              @apply text-sm text-gray-500 dark:text-gray-400 mt-1;

              span {
                @apply line-through;
              }
            }
          }

          .sales-info {
            @apply flex gap-6 text-sm text-gray-500 dark:text-gray-400;
          }
        }

        .product-specs {
          @apply mb-8;

          .spec-item {
            @apply mb-4;

            .spec-name {
              @apply text-gray-700 dark:text-gray-300 mb-2;
            }
          }
        }

        .quantity-section {
          @apply flex items-center gap-4 mb-8;

          .label {
            @apply text-gray-700 dark:text-gray-300;
          }

          .stock {
            @apply text-sm text-gray-500 dark:text-gray-400;
          }
        }

        .service-section {
          @apply mb-8 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg;

          .service-title {
            @apply text-gray-700 dark:text-gray-300 mb-4;
          }

          .service-items {
            @apply grid grid-cols-4 gap-4;

            .service-item {
              @apply flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400;
            }
          }
        }
      }
    }
  }

  .product-content {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm mt-6;

    .detail-tabs {
      @apply bg-white p-6 rounded-lg;

      .detail-content {
        @apply min-h-[400px];
      }

      .reviews-overview {
        @apply flex items-start gap-8 mb-6 p-6 bg-gray-50 rounded-lg;

        .rating-section {
          @apply text-center;

          .rating-score {
            @apply text-4xl font-bold text-primary-600 mb-2;

            small {
              @apply text-base font-normal;
            }
          }
        }

        .rating-tags {
          @apply flex-1 flex flex-wrap gap-2;

          .tag-item {
            @apply cursor-pointer;
          }
        }
      }

      .reviews-list {
        @apply space-y-6;

        .review-item {
          @apply p-6 bg-gray-50 rounded-lg;

          .review-header {
            @apply flex items-start gap-4 mb-4;

            .user-info {
              @apply flex-1;

              .user-name {
                @apply font-medium mb-2;
              }

              .review-meta {
                @apply flex items-center gap-4 text-sm text-gray-500;
              }
            }
          }

          .review-content {
            @apply space-y-4;

            .review-text {
              @apply text-gray-700;
            }

            .review-images {
              @apply grid grid-cols-5 gap-2;

              .image-item {
                @apply rounded-lg overflow-hidden;
              }
            }

            .review-reply {
              @apply bg-gray-100 p-4 rounded-lg text-sm;
            }
          }
        }
      }
    }
  }

  .recommendations {
    .recommendations-grid {
      @apply grid grid-cols-4 gap-6 mt-8;
    }
  }
}
</style>
